from tortoise.expressions import Q

from app.core.crud import CRUDBase
from app.models import CustomerUser
from app.models.marketing import Coupons, CouponsRole
from app.schemas.marketing import CouponsCreate, CouponsUpdate, CouponsCreateIn
from datetime import datetime, timedelta
from app.controllers.customer.users import users_controller


class CouponsController(CRUDBase[Coupons, CouponsCreate, CouponsUpdate]):
    def __init__(self):
        super().__init__(model=Coupons)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        return total, data

    # 用户可使用优惠券
    async def get_user_coupons(self, user_id: int):
        now = datetime.now()
        query = self.model.filter(user_id=user_id,is_used=0).filter(Q(expire_at__isnull=True) | Q(expire_at__gte=now))
        total = await query.count()
        data = query.all()
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: CouponsCreate):
        coupons = await CouponsRole.filter(id=obj_in.coupons_id).first().values()
        obj_in.coupons_price = coupons['value']
        expire_at = coupons['expire_at']
        # 计算过期时间
        current_time = datetime.now()
        new_time = current_time + timedelta(days=expire_at)
        new_time_str = new_time.strftime("%Y-%m-%d %H:%M:%S")
        obj_in.expire_at = new_time_str
        await self.create(obj_in=obj_in)
        await users_controller.update_money(type=3, user_id=obj_in.user_id)
        return True

    async def do_put(self, category_in: CouponsCreateIn):
        user_ids = category_in.user_ids
        coupons = await CouponsRole.filter(id=category_in.coupons_id).first().values("value", "expire_at")
        if user_ids is None:
            users = await CustomerUser.all().values("id")
            user_ids = [user["id"] for user in users]

        for user_id in user_ids:
            coupons_in = {
                "user_id": user_id,
                "coupons_id": category_in.coupons_id,
                "coupons_price": 0,
                "expire_at": "",
                "is_used": 0,
                "order_id": 0,
                "come_type": 1,
                "order_goods_id": 0,
                "remark": category_in.remark,
            }
            coupons_in = CouponsCreate(**coupons_in)
            await self.do_create(obj_in=coupons_in)
            await users_controller.update_money(type=3, user_id=user_id)

        return True

    async def do_update(self, obj_in: CouponsUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        await users_controller.update_money(type=3, user_id=obj_in.user_id)
        return True

    async def do_delete(self, data_id: int):
        user_id = await self.model.filter(id=data_id).first().values("user_id")
        await self.remove(id=data_id)
        await users_controller.update_money(type=3, user_id=user_id['user_id'])
        return True

    ##检测发放的优惠券的过期状态
    async def do_expire(self):
        now  = datetime.utcnow()
        await Coupons.filter(expire_at__lt=now, is_used=0).update(is_used=2)
        return True


coupons_controller =CouponsController()
